﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MyNeighbourhood.Helpers;

namespace MyNeighbourhood.Filters
{
    public class AuthorizeIPAddressAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string ipAddress = HttpContext.Current.Request.UserHostAddress;

          //  ipAddress = "78.90.72.255";

            if (IsIpAddressRestricted(ipAddress.Trim()))
            {
                filterContext.Result = new ViewResult
                {
                    ViewName = "Forbidden"
                };
            }

            base.OnActionExecuting(filterContext);
        }

        private static bool IsIpAddressRestricted(string ipAddress)
        {
            string restrictedRangeString =
              Convert.ToString(ConfigurationManager.AppSettings["RestrictedIPs"]);

            string[] restrictedRange = restrictedRangeString.Trim().Split(new char[] { '-', ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (HelperMethods.IsIpInRange(restrictedRange[0], restrictedRange[1], ipAddress))
            {
                return true;
            }

            return false;
        }

    }
}